package com.citywithincity.api;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.utils.CachedClassUtil;
import com.citywithincity.utils.ClassUtil;
import com.damai.action.IAction;
import com.damai.action.IActionFactory;
import com.damai.action.aop.Interceptor;
import com.damai.annotation.Action;
import com.damai.annotation.Controller;

import javassist.ClassPool;

public class ApiBuildUtil {
	private static Log logger = LogFactory.getLog(ApiBuildUtil.class);
	public static void helpBuildAction(ClassPool classPool,Class<?> controllerClass, Map<String, IAction> routeMap,List<Interceptor> interceptors) throws Exception{
		Controller c = controllerClass.getAnnotation(Controller.class);
		if(c==null){
			logger.info("Controller " + controllerClass.getName() + " do not have anonnation.");
			return;
		}
		String key = c.key();
		if(routeMap.containsKey(key)){
			throw new RuntimeException("Key "
					+ key
					+ " on controller "
					+ controllerClass.getName()
					+ " already exists.");
		}
		
		Method[] methods = ClassUtil.getPublicMethods(controllerClass);
		for (Method method : methods) {
			String routeKey = key + "/" + method.getName();
			if(!routeKey.startsWith("/")){
				routeKey = "/" + routeKey;
			}
			routeMap.put(routeKey, getAction(classPool,controllerClass,method,routeKey,interceptors));
		}
	}
	
	
	public static Class<? extends IActionFactory> getFactoryClass(Class<?> controllerClass, Method method){
		Action action =method.getAnnotation(Action.class); 
		if(action==null){
			action = controllerClass.getAnnotation(Action.class);
		}
		if(action!=null){
			//去这里的
			return action.value();
		}
		return ApiConfig.me().getDefaultActionFactory().getClass();
	}
	
	public static IAction getAction(ClassPool classPool,Class<?> controllerClass, Method method,String key, List<Interceptor> interceptors) {
		
		Action action =method.getAnnotation(Action.class); 
		if(action==null){
			action = controllerClass.getAnnotation(Action.class);
		}
		
		if(action!=null){
			//去这里的
			Class<? extends IActionFactory> factory = action.value();
			IActionFactory value = CachedClassUtil.newInstance(factory);
			return value.createAction(classPool,controllerClass, method,key,interceptors);
		}
		return ApiConfig.me().getDefaultActionFactory().createAction(classPool,controllerClass, method,key,interceptors);
	}

	
}
